package com.dayaokeji.rhythmschoolstudent.client.home.course.task;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bilibili.boxing.model.entity.BaseMedia;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.dayaokeji.rhythmschoolstudent.R;
import com.dayaokeji.rhythmschoolstudent.boxing.BoxingUtil;
import com.dayaokeji.rhythmschoolstudent.client.common.ActivityStackManager;
import com.dayaokeji.rhythmschoolstudent.client.common.ShowBigImageActivity;
import com.dayaokeji.rhythmschoolstudent.client.common.base.App;
import com.dayaokeji.rhythmschoolstudent.client.common.base.common.BaseActivity;
import com.dayaokeji.rhythmschoolstudent.client.common.resource.FileChooserActivity;
import com.dayaokeji.rhythmschoolstudent.client.common.resource.SharedResourceActivity;
import com.dayaokeji.rhythmschoolstudent.client.home.course.adapter.HomeWorkAdapter;
import com.dayaokeji.rhythmschoolstudent.client.home.course.bean.FileBean;
import com.dayaokeji.rhythmschoolstudent.utils.DateUtils;
import com.dayaokeji.rhythmschoolstudent.utils.DialogUtils;
import com.dayaokeji.rhythmschoolstudent.utils.FileUtil;
import com.dayaokeji.rhythmschoolstudent.utils.OpenFileUtils;
import com.dayaokeji.rhythmschoolstudent.utils.ServerCallback;
import com.dayaokeji.rhythmschoolstudent.utils.ToastUtils;
import com.dayaokeji.rhythmschoolstudent.utils.UserUtils;
import com.dayaokeji.server_api.ApiUtils;
import com.dayaokeji.server_api.ServerResponse;
import com.dayaokeji.server_api.api.CourseTaskApi;
import com.dayaokeji.server_api.api.ResourceApi;
import com.dayaokeji.server_api.domain.CourseTask;
import com.dayaokeji.server_api.domain.FileInfo;
import com.dayaokeji.server_api.domain.HomeWorkSubmitBean;
import com.dayaokeji.server_api.domain.SelectTaskDetail;
import com.dayaokeji.server_api.domain.UserInfo;
import com.dayaokeji.server_api.utils.FileFunctionFlag;
import com.facebook.stetho.common.LogUtil;
import com.orhanobut.logger.Logger;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import ir.sohreco.androidfilechooser.FileChooser;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 作业详情
 */
public class CourseTaskDetailActivity extends BaseActivity implements View.OnClickListener {

    private static final String EXTRA_COURSE_TASK = "course_task_entity";
    @BindView(R.id.toolbar)
    Toolbar toolbar;

    private static final CourseTaskApi courseTaskApi = ApiUtils.getApi(CourseTaskApi.class);
    @BindView(R.id.tv_task_content)
    TextView tvTaskContent;
    @BindView(R.id.tv_task_desc)
    TextView tvTaskDesc;
    @BindView(R.id.tv_task_time)
    TextView tvTaskTime;
    @BindView(R.id.rv_files)
    RecyclerView rvFiles;
    private CourseTask courseTask;

    private final RemoteFilesAdapter filesAdapter = new RemoteFilesAdapter();
    private RecyclerView mRecyclerView;
    private HomeWorkAdapter homeWorkAdapter;
    private UserInfo userInfo;
    private LinearLayout addFile;
    private TextView tvSubmit;

    public static void navigation(Context context, CourseTask courseTask) {
        Intent intent = new Intent(context, CourseTaskDetailActivity.class);
        intent.putExtra(EXTRA_COURSE_TASK, courseTask);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_course_task_detail);
        setSupportActionBar(toolbar);
        init();
    }


    private void init() {
        initView();
        initData();
        setOnListener();
    }

    private void initView() {
        mRecyclerView = findViewById(R.id.recycler_view);
        initRecyclerView();
        addFile = findViewById(R.id.ll_add_file);
        addFile.setOnClickListener(this);
        tvSubmit = findViewById(R.id.submit);
        tvSubmit.setOnClickListener(this);
        rvFiles.setLayoutManager(new GridLayoutManager(this, 4));
        rvFiles.setAdapter(filesAdapter);
    }

    private void initRecyclerView() {
        homeWorkAdapter = new HomeWorkAdapter();
        homeWorkAdapter.setNewData(filesName);
        homeWorkAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.iv_delete:
                    if (state == 3) {
                        ToastUtils.info("已批阅作业，无法删除！");
                        return;
                    }
                    DialogUtils.getAlertDialog(CourseTaskDetailActivity.this, "", "确定删除这个文件吗?", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Map<String, String> params = new HashMap<>();
                            params.put("id", filesName.get(position).getFileId() + "");
                            adapter.getData().remove(position);
                            adapter.notifyItemRemoved(position);

                            resourceApi.delete(params).enqueue(new ServerCallback<Void>() {
                                @Override
                                public void onResponse(boolean success, ServerResponse<Void> response) {
                                }
                            });
                        }
                    });
                    break;

                    case R.id.tv_room_name:
                        FileBean bean = (FileBean) adapter.getData().get(position);
                        if (bean.getFile() != null) {
                            File file = bean.getFile();
                            if (!file.exists() || file.isDirectory()) {
                                return;
                            }
                            OpenFileUtils.openFileByPath(CourseTaskDetailActivity.this, file.getAbsolutePath());
                        } else {
                            File fil = new File(FileUtil.RESOURCE_DIR + bean.getName());
                            if (fil.exists() && fil.isFile()) {
                                OpenFileUtils.openFileByPath(CourseTaskDetailActivity.this, fil.getAbsolutePath());
                                return;
                            }
                            FileInfo fileInfo = new FileInfo();
                            fileInfo.setName(bean.getName());
                            final ProgressDialog progressDialog = new ProgressDialog(CourseTaskDetailActivity.this);
                            progressDialog.setTitle("正在下载" + fileInfo.getName());
                            progressDialog.show();
                            resourceApi.download(bean.getFileId() + "").enqueue(new Callback<ResponseBody>() {
                                @Override
                                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                                    if (response.isSuccessful()) {
                                        FileUtil.saveFile(response.body(), fileInfo);
                                    } else {
                                        ToastUtils.error(getString(R.string.file_download_failure));
                                    }
                                    if (!CourseTaskDetailActivity.this.isFinishing() && progressDialog != null) {
                                        progressDialog.dismiss();
                                    }
                                }

                                @Override
                                public void onFailure(Call<ResponseBody> call, Throwable t) {
                                    ToastUtils.error(getString(R.string.file_download_failure));
                                    progressDialog.dismiss();
                                }
                            });
                        }

                    break;
                }
            }
        });

        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.setAdapter(homeWorkAdapter);
    }

    private int state = 0;

    @SuppressLint("SetTextI18n")
    private void initData() {
        userInfo = UserUtils.getUserInfo();
        courseTask = (CourseTask) getIntent().getSerializableExtra(EXTRA_COURSE_TASK);
        SelectTaskDetail selectTaskDetail = new SelectTaskDetail();
        selectTaskDetail.setUserid(userInfo.getId());
        selectTaskDetail.setClassworkId(courseTask.getId() + "");
        selectTaskDetail.setCourseId(courseTask.getCourseId());
        courseTaskApi.selectTask(userInfo.getId(), courseTask.getCourseId(), courseTask.getId() + "").enqueue(new ServerCallback<CourseTask>(this, "正在获取数据...") {

            @Override
            public void onResponse(boolean success, ServerResponse<CourseTask> response) {
                if (success) {
                    String courseId = courseTask.getCourseId();
                    courseTask = response.getBody();
                    if (courseTask == null) {
                        ToastUtils.warning(R.string.data_incorrect);
                        ActivityStackManager.finish();
                        return;
                    }
                    courseTask.setCourseId(courseId);
                    tvTaskContent.setText(courseTask.getContent());
                    String describe = courseTask.getDescribe();
                    if (TextUtils.isEmpty(describe)) {
                        tvTaskDesc.setVisibility(View.GONE);
                    }
                    tvTaskDesc.setText(courseTask.getDescribe());
                    long finishTime = Long.parseLong(courseTask.getFinishTime());
                    String finishFormat = DateUtils.format(finishTime, DateUtils.FORMAT_DATE);
                    tvTaskTime.setText("截止时间： " + finishFormat);
                    if (courseTask.getResourceList().size() > 0) {
                        filesAdapter.setNewData(courseTask.getResourceList());
                    }
                    TextView subState = findViewById(R.id.tv_sub_state);
                    TextView tvGrade = findViewById(R.id.tv_grade);
                    EditText tvAnsaw = findViewById(R.id.ed_content);
                    tvAnsaw.setText(courseTask.getAnswer());
                    switch (courseTask.getUclasswstatus()) {
                        case 1:
                            subState.setText("提交状态：待提交");
                            state = 1;
                            break;
                        case 2:
                            subState.setText("提交状态：待批阅");
                            state = 2;
                            break;
                        case 3:
                            subState.setText("提交状态：已批阅");
                            tvGrade.setText(courseTask.getScore() + "");
                            tvGrade.setVisibility(View.VISIBLE);
                            addFile.setVisibility(View.GONE);
                            state = 3;
                            tvAnsaw.setEnabled(false);
                            tvSubmit.setVisibility(View.GONE);
                            break;
                    }

                    List<CourseTask.UserResourceListBean> userResourceList = courseTask.getUserResourceList();
                    if (userResourceList != null) {
                        for (CourseTask.UserResourceListBean userResourceListBean : userResourceList) {
                            FileBean fileBean = new FileBean();
                            fileBean.setFileId(userResourceListBean.getId());
                            fileBean.setName(userResourceListBean.getName());
                            filesName.add(fileBean);
                        }
                        homeWorkAdapter.notifyDataSetChanged();
                    }
                } else {
                    ToastUtils.error("获取数据失败");
                }
            }
        });


    }

    private void setOnListener() {
        filesAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Integer imgId = (Integer) adapter.getData().get(position);
                ShowBigImageActivity.navigation(CourseTaskDetailActivity.this, imgId);
            }
        });
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_add_file://添加附件
                if (state == 3) return;
                Dialog dialog = new Dialog(this);
                View view = View.inflate(this, R.layout.dialog_photo_file_upload, null);
                TextView addPhoto = view.findViewById(R.id.tv_add_photo);
                TextView addFile = view.findViewById(R.id.tv_add_file);

                dialog.setContentView(view);
                addPhoto.setOnClickListener(v1 -> {
                    BoxingUtil.startSingleChooseImage(this, PHOTO_REQUE);
                    dialog.dismiss();
                });

                addFile.setOnClickListener(v2 -> {
                    startActivityForResult(new Intent(CourseTaskDetailActivity.this, FileChooserActivity.class), FILE_REQUER);
                    dialog.dismiss();
                });
                dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
                dialog.show();
                break;
            case R.id.submit://提交
                EditText ansaw = findViewById(R.id.ed_content);
                String ans = ansaw.getText().toString();
                CourseTaskApi courseTaskApi = ApiUtils.getApi(CourseTaskApi.class);
                HomeWorkSubmitBean homeWorkSubmitBean = new HomeWorkSubmitBean();
                homeWorkSubmitBean.setAnswer(ans);
                homeWorkSubmitBean.setCourseId(courseTask.getCourseId());
                homeWorkSubmitBean.setClassworkId(courseTask.getId() + "");
                homeWorkSubmitBean.setUserId(userInfo.getId());
                List<Integer> integerList = new ArrayList<>();
                for (FileBean fileBean : filesName) {
                    integerList.add(fileBean.getFileId());
                }
                homeWorkSubmitBean.setListResourceId(integerList);
                courseTaskApi.submit(homeWorkSubmitBean).enqueue(new ServerCallback<Integer>(this, "正在提交...") {
                    @Override
                    public void onResponse(boolean success, ServerResponse<Integer> response) {
                        if (success) {
                            ToastUtils.success("提交成功");
                            finish();
                        }
                    }
                });
                for (FileBean fileBean : filesName) {
                    LogUtil.e(fileBean.getFileId() + "");
                }

        }
    }

    Integer FILE_REQUER = 9;
    Integer PHOTO_REQUE = 95;
    Call<ServerResponse<List<Integer>>> uploadAvatarCall;
    private static final ResourceApi resourceApi = ApiUtils.getApi(ResourceApi.class);
    List<FileBean> filesName = new ArrayList<>();

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null) return;
        if (PHOTO_REQUE == requestCode) {
            final List<BaseMedia> baseMediaList = BoxingUtil.getResultFileList(data);
            if (baseMediaList == null || baseMediaList.size() < 1) return;
            File file = new File(baseMediaList.get(0).getPath());
            resultFile(file, this);

        } else if (FILE_REQUER == requestCode) {
            String[] stringArrayExtra = data.getStringArrayExtra(FileChooserActivity.EXTRA_CHOOSER_FILE_PATHS);

            if (stringArrayExtra == null || stringArrayExtra.length < 1) {
                return;
            }
            File file = new File(stringArrayExtra[0]);
            resultFile(file, this);
        }
    }

    private void resultFile(File file, CourseTaskDetailActivity courseTaskDetailActivity) {
        FileBean fileBean = new FileBean();
        fileBean.setName(file.getName());
        fileBean.setFile(file);
        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Part filePart = MultipartBody.Part.createFormData("myfiles", file.getName(), requestBody);

        uploadAvatarCall = resourceApi.upload(filePart,
                RequestBody.create(MediaType.parse("text/plain"), "9"),
                RequestBody.create(MediaType.parse("text/plain"), "作业附件"),
                RequestBody.create(MediaType.parse("text/plain"), String.valueOf(FileFunctionFlag.JOB_FILE)),
                RequestBody.create(MediaType.parse("text/plain"), userInfo.getId()),
                RequestBody.create(MediaType.parse("text/plain"), String.valueOf(Boolean.FALSE.booleanValue())));
        uploadAvatarCall.enqueue(new ServerCallback<List<Integer>>(courseTaskDetailActivity, "正在上传文件...") {
            @Override
            public void onResponse(boolean success, ServerResponse<List<Integer>> response) {
                if (success) {
                    Logger.d("updaload avatar..." + response.toString());
                    fileBean.setFileId(response.getBody().get(0));
                    filesName.add(fileBean);
                    homeWorkAdapter.notifyDataSetChanged();
                }
            }
        });
    }
}
